﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AL.Helper
{


    public class Polling
    {
        private int _interval = 1000;

        public int Interval
        {
            get { return _interval; }
            set { _interval = value; }
        }
        public bool IsRunning { get; internal set; }

        public void Start(Action action)
        {
            if (this.IsRunning)
            {
                return;
            }

            this.IsRunning = true;

            Task.Factory.StartNew(() =>
            {
                while (this.IsRunning)
                {
                    action.Invoke();
                    SpinWait.SpinUntil(() => !this.IsRunning, this.Interval);
                }
            });
        }

        public void Stop()
        {
            if (!this.IsRunning)
            {
                return;
            }
            this.IsRunning = false;
        }
    }







    //public partial class Form1 : Form
    //{
    //    public Form1()
    //    {
    //        InitializeComponent();
    //        m_SynchronizationContext = SynchronizationContext.Current;
    //    }

    //    private SynchronizationContext m_SynchronizationContext;

    //    private Polling _polling = new Polling();
    //    private int _counter = 0;

    //    private void button1_Click(object sender, EventArgs e)
    //    {
    //        this._polling.Interval = int.Parse(this.textBox1.Text);
    //        this._polling.Start(() =>
    //        {
    //            this._counter++;
    //            m_SynchronizationContext.Post(a => { this.label1.Text = this._counter.ToString(); }, null);
    //        });
    //    }

    //    private void button2_Click(object sender, EventArgs e)
    //    {
    //        this._polling.Stop();
    //    }
    //}




}
